package com.lyy.cloud.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author lcj
 * @version 1.0
 * @description okhttp get post工具类
 * @Create 2017-06-16
 */
@Slf4j
public class OkHttpUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpUtil.class);
    private static final OkHttpClient CLIENT;

    static {
        CLIENT = new OkHttpClient.Builder()
                //连接超时
                .connectTimeout(10, TimeUnit.SECONDS)
                //写超时
                .writeTimeout(10, TimeUnit.SECONDS)
                //读超时
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }

   public enum OkHttpMethod {
        POST,
        PUT,
        DELETE
    }


    /**
     * get请求,支持http和https
     * @param url 地址,比如: http://wwww.baidu.com
     * @param params 参数,可以为null
     * @param headers 请求头,可以为null
     * @return
     */
    public static String get(String url,Map<String,Object> params,Map<String,String> headers){
        return getAuthorization(url,params,headers,null);
    }
    /**
     * get请求,支持http和https 需要登陆状态
     * @param url 地址,比如: http://wwww.baidu.com
     * @param params 参数,可以为null
     * @param headers 请求头,可以为null
     * @return
     */
    public static String getAuthorization(String url,Map<String,Object> params,Map<String,String> headers ,String credential){
        //Builder对象
        Request.Builder builder = new Request.Builder();

        //处理参数
        if(null != params && params.size() > 0){
            StringBuilder stringBuilder = new StringBuilder("?");
            params.forEach((k,v) -> {
                stringBuilder.append(k).append("=").append(v).append("&");
            });
            String param = stringBuilder.toString();
            url += param.substring(0,param.lastIndexOf("&"));
        }

        //处理请求头
        if(null != headers && headers.size() > 0){
            headers.forEach((k,v) -> builder.header(k,v));
        }

        Request request = null;
        if(StringUtils.isNotBlank(credential)){
            request = builder.url(url).header("Authorization", credential).build();
        }else{

            request = builder.url(url).build();
        }
        //创建响应对象
        try {
            Response response = CLIENT.newCall(request).execute();
            if(!response.isSuccessful()){
                LOGGER.error("发送get请求失败,状态码:{}",response.code());
                return "";
            }
            return response.body().string();
        } catch (IOException e) {
            LOGGER.error("发送get请求失败,原因:{}",e);
            return "";
        }
    }
    /**
     * post,put,delete请求,支持http和https
     * @param url 地址,比如: http://wwww.baidu.com
     * @param params 参数,可以为null
     * @param headers 请求头,可以为null
     * @param okHttpMethod 请求方式
     * @return
     */
    public static String postOrPutOrDelete(String url,Object params,Map<String,String> headers,OkHttpMethod okHttpMethod) {
        return postOrPutOrDeleteAuthorization(url,params,headers,okHttpMethod,null);
    }

    /**
     * post,put,delete请求,支持http和https 需要登陆
     * @param url 地址,比如: http://wwww.baidu.com
     * @param params 参数,可以为null
     * @param headers 请求头,可以为null
     * @param okHttpMethod 请求方式
     * @param credential
     */
    public static String postOrPutOrDeleteAuthorization(String url,Object params,Map<String,String> headers,OkHttpMethod okHttpMethod ,String credential){
        //Builder对象
        Request.Builder builder = new Request.Builder();

        //处理请求头
        if(null != headers && headers.size() > 0){
            headers.forEach((k,v) -> builder.header(k,v));
        }

        //处理参数
        if(null != params){
        	String content = ""; 
        	if(content instanceof String) {
        		content = params.toString();
        	}else {
        		content = JSON.toJSONString(params);
        	}
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),content);
            switch (okHttpMethod){
                case POST:
                    builder.post(body);
                    break;
                case PUT:
                    builder.put(body);
                    break;
                case DELETE:
                    builder.delete(body);
                    break;
                default:
                    builder.post(body);
                    break;

            }
        }else {
            switch (okHttpMethod){
                case DELETE:
                default:
                    builder.delete();
                    break;

            }
        }

        Request request = null;
        if(StringUtils.isNotBlank(credential)){
            request = builder.url(url).header("Authorization", credential).build();
        }else{
            request = builder.url(url).build();
        }
        //创建响应对象
        try {
            Response response = CLIENT.newCall(request).execute();
            if(!response.isSuccessful()){
                LOGGER.error("发送请求失败,状态码:{}，url={}，method={}",response.code(),url,okHttpMethod);
                return "";
            }
            return response.body().string();
        } catch (IOException e) {
            LOGGER.error("发送请求失败,原因:{}，url={}，method={}",e.getCause(),url,okHttpMethod);
            return "";
        }
    }

    /**
    * @Description: 获取资源
    * @param path
    * @return java.lang.String
    * @author liushiwei
    * @date 2019/9/12 14:53
    */
    public static String getContentByUrl(String path) throws IOException {

        String content = null;
        InputStream in = null;
        BufferedReader bufr = null;
        InputStreamReader isr = null;
        try {
            URL url = new URL(path);
            in = url.openStream();
            isr = new InputStreamReader(in);
            bufr = new BufferedReader(isr);
            String str;
            while ((str = bufr.readLine()) != null) {
                if(StringUtils.isNotBlank(content)){
                    content = content+str;
                }else{
                    content = str;
                }
            }

        } catch (Exception e) {
            log.error("获取资源异常",e);
        } finally {
            if( null != bufr){
                bufr.close();
            }
            if( null != isr ){
                isr.close();
            }
            if( null != in ){
                in.close();
            }
        }
        return content;
    }

    /**
     * 获取登陆证书
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public static String getCredential(String username, String password){
        String credential = null;
        if(StringUtils.isNotBlank(username) || StringUtils.isNotBlank(password) ){
            credential = Credentials.basic(username, password);
        }
        return credential;
    }

}
